<template>
  <div class="favorites">
    <header class="header">
      <img
        src="@/assets/images/back_arrow.png"
        alt=""
        class="back-arrow"
        @click="goBack"
      />
      <span class="title">专业收藏夹</span>
    </header>
    <div
      class="school-container"
      ref="schoolContainer"
      @scroll="debouncedCheckScrollBottom"
      v-if="favoriteMajorList.length > 0 || isLoading"
    >
      <table class="favorite-table" v-if="favoriteMajorList.length > 0">
        <thead>
          <tr>
            <th style="width: 16%">学科门类</th>
            <th style="width: 16%">专业类别</th>
            <th style="width: 45%">专业名称</th>
            <th style="width: 15%">专业代码</th>
            <th style="width: 8%">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="(item, idx) in favoriteMajorList"
            :key="idx"
            @click="gotoMajorDetail(item)"
          >
            <td style="width: 16%">{{ item.topName }}</td>
            <td style="width: 16%">{{ item.parentName }}</td>
            <td style="width: 45%">{{ item.tagName }}</td>
            <td style="width: 15%">{{ item.tagCode }}</td>
            <td style="width: 8%">
              <img
                :src="item.isCollect == 1 ? starFill : blueStarPlus"
                alt="收藏"
                style="width: 24px; height: 24px"
                @click.stop="handleStar(item)"
              />
            </td>
          </tr>
        </tbody>
      </table>
      <div class="loading" v-if="isLoading">加载中...</div>
    </div>
    <div v-if="favoriteMajorList.length == 0 && !isLoading" class="empty">
      <Empty />
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { campusCollectTags, campusCollect } from '@/api/majorSearch';
import antiShake from '@/utils/antiShake.js';
import Empty from '@/components/Empty.vue';
import starFill from '@/assets/images/starFill.png';
import blueStarPlus from '@/assets/images/blueStarPlus.png';

const router = useRouter();
const favoriteMajorList = ref([]);
const schoolContainer = ref(null);
const pageNum = ref(0);
const pageSums = ref(100);

const gotoMajorDetail = (item) => {
  router.push({
    name: 'MajorDetail',
    query: {
      positionTagId: item.positionTagId,
      tagName: item.tagName,
      cateType: item.cateType,
    },
  });
};

const handleStar = async (item) => {
  const params = {
    dataId: item.positionTagId,
    dataType: 12,
    action: item.isCollect == 1 ? 0 : 1, // 1新增收藏  0取消收藏
  };
  const res = await campusCollect(params);
  if (res.code == 200) {
    showToast(params.action == 1 ? '收藏成功！' : '已取消收藏');
    item.isCollect = params.action == 1 ? 1 : 0;
  }
};

const checkScrollBottom = () => {
  const container = schoolContainer.value;
  if (container) {
    const { scrollTop, scrollHeight, clientHeight } = container;
    // 当滚动到底部时触发通知
    if (scrollTop + clientHeight >= scrollHeight - 10) {
      campusCollectTagsFn();
    }
  }
};

const debouncedCheckScrollBottom = antiShake(checkScrollBottom, 100);

const isLoading = ref(false);
const hasMore = ref(true);

const campusCollectTagsFn = async () => {
  if (isLoading.value || !hasMore.value) return; // 防止重复请求或已无更多数据
  isLoading.value = true;

  const params = {
    pageSize: 17,
    pageNo: pageNum.value,
  };

  try {
    const res = await campusCollectTags(params);
    if (res.code === 200) {
      // 总页数
      const totalPages = res.pageparam.pages || 1;
      pageSums.value = totalPages;

      // 数据处理
      res.data.forEach((item) => (item.isCollect = 1));
      const data = res.data || [];
      if (pageNum.value === 1) {
        favoriteMajorList.value = data;
      } else {
        favoriteMajorList.value = [...favoriteMajorList.value, ...data];
      }

      // 判断是否还有更多
      if (pageNum.value >= totalPages || data.length < params.pageSize) {
        hasMore.value = false;
      } else {
        pageNum.value += 1;
      }
    } else {
      hasMore.value = false;
    }
  } catch (e) {
    showToast('加载失败，请重试');
  } finally {
    isLoading.value = false;
  }
};

const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  // 确保在滚动事件监听中使用防抖后的函数
  if (schoolContainer.value) {
    schoolContainer.value.addEventListener(
      'scroll',
      debouncedCheckScrollBottom
    );
  }

  campusCollectTagsFn();
});
</script>

<style scoped lang="scss">
.favorites {
  height: 100vh;
  background: linear-gradient(180deg, #e8f9ff 0%, #f4f6f8 100%);
  padding: 0 60px 0 60px;
  overflow: hidden;
  .header {
    display: flex;
    align-items: center;
    padding: 20px 0;
    position: relative;
    .title {
      font-weight: 400;
      font-size: 30px;
      color: #333333;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }
    .back-arrow {
      width: 48px;
      height: 48px;
    }
  }
  .school-container {
    display: block;
    overflow-y: auto;
    height: calc(100vh - 108px);
    padding: 0;
    margin-top: 16px;
    border-radius: 16px;
    .favorite-table {
      width: 100%;
      border-collapse: separate;
      border-spacing: 0;
      background: #fff;
      border-radius: 16px;

      th,
      td {
        /* 去掉单元格的所有边框 */
        border: none;
        text-align: left;
        color: #666;
        &:first-child {
          padding-left: 60px;
        }
      }
      th {
        position: sticky;
        top: 0px;
        z-index: 2;
        background: #f5f8fc;
        font-size: 24px;
        font-weight: bold;
        padding: 13px 0 13px 32px;
      }
      td {
        font-size: 26px;
        padding: 28px 0 28px 32px;
      }
      tr {
        transition: background 0.2s;
        &:hover {
          background: #f0f7ff;
        }
        /* 给每一行加底部分隔线，最后一行不加 */
        &:not(:last-child) td {
          border-bottom: 1px solid #e6e6e6;
        }
      }
    }
    /* 隐藏所有浏览器滚动条 */
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE/Edge */
    &::-webkit-scrollbar {
      display: none;
    } /* Chrome/Safari/Opera */
    .loading {
      grid-column: 1 / -1;
      width: 100%;
      text-align: center;
      font-size: 24px;
      color: #666666;
      padding: 0 0 40px 0;
    }
  }
  .empty {
    height: 780px;
  }
}
</style>
